package com.xuanwei.web.controller;

import com.github.tobato.fastdfs.exception.FdfsUnsupportImageTypeException;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.response.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * @Author jiangyong
 * @Description TODO 异常处理类
 * @Date 2019/4/23 15:34
 **/
@RestControllerAdvice
@Slf4j
public class ExceptionController {

    /**
     * 请求方式错误
     * @param request request
     * @return 响应
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResultVO notSupportedException(HttpServletRequest request) {
      return ResultVO.failResult(request.getMethod()+"请求方式错误");
    }

    /**
     * 登陆异常
     * @return 响应
     */
    @ExceptionHandler(value = BadCredentialsException.class)
    public ResultVO badCredentialsException() {
        return ResultVO.failResult("用户名或密码错误");
    }


    /**
     * fastDfs上传图片异常
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = FdfsUnsupportImageTypeException.class)
    public ResultVO fdfsUnsupportImageTypeException(Exception e){
        return ResultVO.failResult(e.getMessage());
    }

    /**
     * 总异常
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = Exception.class)
    public ResultVO exception(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        return ResultVO.failResult("系统异常");
    }


    /**
     * 自定义异常
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = XwException.class)
    public ResultVO xwException(Exception e){
        return ResultVO.failResult(e.getMessage());
    }

    /**
     * 参数校验
     * @param e e
     * @return 响应
     */
    @ExceptionHandler(value = BindException.class)
    public ResultVO bindException(BindException e){
        List<ObjectError> allErrors = e.getAllErrors();
        String defaultMessage = allErrors.get(0).getDefaultMessage();
        return ResultVO.failResult(defaultMessage);
    }

    /**
     * 方法上参数校验
     * @param e  异常
     * @return 响应
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultVO bindException(ConstraintViolationException e){
        return ResultVO.failResult(e.getMessage());
    }

}
